package com.ziq.zcamp.wxapi;

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.ziq.zcamp.manager.WXAccount;

/**
 * 微信支付Activity
 */
public class WXPayEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
    private static final String TAG = "WXPayEntryActivity";

    private IWXAPI api;
    //支付结果回调
    public static IWXPayCallback callback = null;

    /**
     * 简单调用方式
     *
     * @param code
     * @param msg
     */
    private static void onResult(int code, String msg) {
        if (null == callback) { return; }
        callback.onResult(code, msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清理回调，以防泄露
        callback = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(
                this,
                WXAccount.APP_ID,
                true
        );
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) { }

    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (resp.errCode == 0) {
                onResult(0, "微信支付成功");
            } else {
                if (resp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
                    onResult(-2, "微信支付用户取消");
                } else {
                    onResult(-1, "微信支付失败(err=" + resp.errCode + ", msg=" + resp.errStr + ")");
                }
            }
        }
        finish();
    }

    public interface IWXPayCallback {
        void onResult(int code, String msg);
    }
}